#!/usr/bin/env python2.5

# what is this ? Cookie: dev_appserver_login="nickmilon@gmail.com:False:119222404092061841222"; django_language=en
#    #print "HEADERS\n" + str(self.response.headers)
#    print dir(self.request)   #get_all("Accept") 
#    print self.request
#    for  key in self.request.environ.keys():
#         print [key, self.request.environ[key]]

from google.appengine.ext import db

import zipfile    
flagsFile = zipfile.ZipFile("res/flagsres.zip", "r")
 


#from google.appengine.api import images
#rawimgdata= file("res/testSprite1", 'rb')
#rawimgdata=rawimgdata.read()
#curImg = images.Image(rawimgdata) 
 
import sys
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class countries(db.Model):
    cc = db.StringProperty() #  IntegerProperty() #required=True 
    flagBig = db.BlobProperty()
    cc= db.StringProperty()      

def countryset(cc,flagB=None):
    try:
        cc=cc.upper() 
        newcntr=countries(key_name=  cc)
        newcntr.cc=cc
        if flagB is not None:newcntr.flagBig = flagB
        rtkey=newcntr.put()
        rt=  newcntr.to_xml()
        return [rtkey, rt]
    except:
        return  'Err:' +  str(sys.exc_info())

class reqErr(webapp.RequestHandler): 
    def get(self, arg):    
        print 'ERROR REQ'  +arg 
        
class country(webapp.RequestHandler): 
    def get(self, lng, cntr):   
        self.response.headers['Content-Type'] = 'image/jpeg'    
        ccflag=flagsFile.read("ccflags/gr.png")
        self.response.out.write (ccflag)          
 
class cntrput(webapp.RequestHandler): 
    def get(self, lng, cntr, getOrSet):    
        if getOrSet=='set': 
            cnt=0
            for name in flagsFile.namelist():
                if not name.endswith('/'):
                    cnt += 1
                    cc=name[-6:-4]
                    if cnt < 400:  
                        ccflag=flagsFile.read(name)
                        rt= countryset(cc, ccflag) 
            self.response.out.write (['ok', lng, cntr])
        else:
            #rt = db.GqlQuery("SELECT * FROM countries WHERE cc = :1 , ORDER BY cc DESC, 'KI'") 
            rt = db.GqlQuery("SELECT * FROM countries " + 
                  "WHERE cc = :1 " +
                  "ORDER BY cc DESC",
                  cntr) 
            for it in rt:
                #print it.to_xml()
                self.response.headers['Content-Type'] = 'image/jpeg'  
                self.response.out.write (it.flagBig)
      


application = webapp.WSGIApplication(
                                     [ 
                                      ('/geo/(?P<lang>en|el|de)/(?P<country>.*?)/*', country),  
                                      ('/srv/(en)/flg/(..)/(get|set)', cntrput), 
                                      ('(.*)', reqErr)
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main() 
